<template>
  <div class="h-full flex-1 flex flex-col p-6 overflow-auto">
    <!-- 页面标题 -->
    <div class="text-center mb-6 flex-shrink-0">
      <h1 class="text-2xl font-bold mb-2 flex items-center justify-center animate-glow"
        :class="themeState.isLight ? 'text-gray-900' : 'text-white'">
        <Sparkles class="w-6 h-6 mr-3 text-electric-500" />
        {{ ts('AI智能咨询') }}
      </h1>
      <p class="text-electric-500 text-sm">{{ ts('基于大模型的政策智能解答系统') }}</p>
    </div>

    <!-- 主要内容区域 -->
    <div class="flex-1 flex gap-6 min-h-0">
      <!-- 左侧聊天区域 -->
      <div class="flex-1 flex flex-col glass-card min-h-0">
        <!-- 消息显示区域 -->
        <div class="flex-1 p-4 overflow-y-auto space-y-4 min-h-[500px]" ref="chatContainer">
          <div v-for="message in messages" :key="message.id" :class="[
            'flex',
            message.type === 'user' ? 'justify-end' : 'justify-start'
          ]">
            <div :class="[
              'max-w-[70%] flex items-start space-x-3',
              message.type === 'user' ? 'flex-row-reverse space-x-reverse' : ''
            ]">
              <div :class="[
                'w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0',
                message.type === 'user'
                  ? 'bg-tech-blue-500 text-white'
                  : 'bg-electric-500 text-cyber-50'
              ]">
                <User v-if="message.type === 'user'" class="w-4 h-4" />
                <Bot v-else class="w-4 h-4" />
              </div>
              <div :class="[
                'rounded-xl p-4 relative group',
                message.type === 'user'
                  ? 'bg-tech-blue-500 text-white'
                  : 'glass-card text-white border-electric-500/30'
              ]">
                <p class="whitespace-pre-line" v-html="message.content"></p>
                <p class="text-xs opacity-70 mt-2">
                  {{ formatTime(message.timestamp) }}
                </p>

                <!-- 语音播放按钮 - 只对bot消息显示 -->
                <button v-if="message.type === 'bot'" @click="playMessageAudio(message)" :disabled="isPlayingAudio"
                  class="absolute top-2 right-2 p-1 rounded-full bg-white/10 hover:bg-white/20 transition-all opacity-0 group-hover:opacity-100"
                  :class="currentPlayingMessage === message.id && isPlayingAudio ? 'bg-electric-500/50' : ''">
                  <svg v-if="!(currentPlayingMessage === message.id && isPlayingAudio)" class="w-4 h-4" fill="none"
                    stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                      d="M15.536 8.464a5 5 0 010 7.072m2.828-9.9a9 9 0 010 14.142M8 21l4-4h5.5a.5.5 0 00.5-.5v-9a.5.5 0 00-.5-.5H12l-4-4v18z">
                    </path>
                  </svg>
                  <svg v-else class="w-4 h-4 animate-pulse" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                      d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                      d="M9 10a1 1 0 011-1h4a1 1 0 011 1v4a1 1 0 01-1 1h-4a1 1 0 01-1-1v-4z"></path>
                  </svg>
                </button>
              </div>
            </div>
          </div>

          <!-- 加载状态 -->
          <div v-if="isLoading" class="flex justify-start">
            <div class="flex items-start space-x-3">
              <div class="w-8 h-8 rounded-full bg-electric-500 text-cyber-50 flex items-center justify-center">
                <Bot class="w-4 h-4" />
              </div>
              <div class="glass-card text-white border-electric-500/30 rounded-xl p-4">
                <div class="flex items-center space-x-2">
                  <div class="w-2 h-2 bg-electric-500 rounded-full animate-bounce"></div>
                  <div class="w-2 h-2 bg-electric-500 rounded-full animate-bounce" style="animation-delay: 0.1s"></div>
                  <div class="w-2 h-2 bg-electric-500 rounded-full animate-bounce" style="animation-delay: 0.2s"></div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 输入区域 -->
        <div class="border-t border-electric-500/30 p-4 flex-shrink-0">
          <div class="flex space-x-3">
            <div class="flex-1 relative">
              <input v-model="inputMessage" type="text"
                :placeholder="recording ? ts('正在录音中...点击麦克风结束') : ts('请输入您的政策问题...')"
                class="cyber-input w-full py-3 px-4 pr-12" @keypress="handleKeyPress" :disabled="isLoading"
                :class="recording ? 'border-red-500 glow-red' : ''" />

              <!-- 语音按钮 -->
              <button @click="toggleRecording" :disabled="isLoading" :class="[
                'absolute right-3 top-1/2 transform -translate-y-1/2 p-2 rounded-full transition-all duration-200',
                recording
                  ? 'bg-red-500 text-white animate-pulse'
                  : 'bg-white/10 text-electric-500 hover:bg-electric-500/20'
              ]">
                <svg v-if="!recording" class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                    d="M19 11a7 7 0 01-7 7m0 0a7 7 0 01-7-7m7 7v4m0 0H8m4 0h4m-4-8a3 3 0 01-3-3V5a3 3 0 116 0v6a3 3 0 01-3 3z">
                  </path>
                </svg>
                <svg v-else class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                    d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                    d="M9 10a1 1 0 011-1h4a1 1 0 011 1v4a1 1 0 01-1 1h-4a1 1 0 01-1-1v-4z"></path>
                </svg>
              </button>
            </div>

            <button @click="sendMessage" :disabled="isLoading || (!inputMessage.trim() && !recording)"
              class="cyber-button flex items-center space-x-2 px-6 py-3">
              <Send class="w-5 h-5" />
              <span>{{ ts('发送') }}</span>
            </button>
          </div>

          <!-- 录音状态指示 -->
          <div v-if="recording" class="mt-2 flex items-center justify-center space-x-2 text-electric-500 text-sm">
            <div class="flex space-x-1">
              <div class="w-2 h-2 bg-red-500 rounded-full animate-bounce"></div>
              <div class="w-2 h-2 bg-red-500 rounded-full animate-bounce" style="animation-delay: 0.1s"></div>
              <div class="w-2 h-2 bg-red-500 rounded-full animate-bounce" style="animation-delay: 0.2s"></div>
            </div>
            <span>{{ ts('正在录音中...再次点击麦克风结束') }}</span>
          </div>

          <!-- 语音识别结果预览 -->
          <div v-if="speechResult && !recording" class="mt-2 p-2 bg-white/5 rounded-lg">
            <div class="flex items-center justify-between">
              <span class="text-white/70 text-sm">{{ ts('语音识别结果:') }}</span>
              <button @click="speechResult = ''" class="text-white/50 hover:text-white text-xs">{{ ts('清除') }}</button>
            </div>
            <p class="text-white text-sm mt-1">{{ speechResult }}</p>
          </div>
        </div>
      </div>

      <!-- 右侧信息面板 -->
      <div class="w-80 flex flex-col space-y-4 overflow-y-auto min-h-[600px]">
        <!-- 常见问题（折叠式） -->
        <div class="glass-card p-3">
          <button @click="showQuestions = !showQuestions"
            class="w-full flex items-center justify-between text-lg font-semibold text-white mb-3">
            <div class="flex items-center">
              <MessageSquare class="w-5 h-5 mr-2 text-tech-blue-400" />
              {{ ts('常见问题') }}
            </div>
            <ChevronDown :class="[
              'w-5 h-5 transition-transform duration-200',
              showQuestions ? 'rotate-180' : ''
            ]" />
          </button>

          <div v-if="showQuestions" class="space-y-2 max-h-40 overflow-y-auto">
            <!-- 通用政策问题 -->
            <div class="mb-2">
              <h5 class="text-sm font-medium text-electric-500 mb-2">💼 {{ ts('通用政策') }}</h5>
              <div class="space-y-1">
                <button v-for="(question, index) in generalQuestions.slice(0, 2)" :key="'general-' + index"
                  @click="selectQuestion(question)"
                  class="w-full text-left p-2 rounded-lg bg-white/5 hover:bg-white/10 text-white/70 hover:text-white transition-all duration-200 text-xs">
                  {{ ts(question) }}
                </button>
              </div>
            </div>

            <!-- 博士后问题 -->
            <div class="mb-2">
              <h5 class="text-sm font-medium text-electric-500 mb-2">🎓 {{ ts('博士后政策') }}</h5>
              <div class="space-y-1">
                <button v-for="(question, index) in postdocQuestions.slice(0, 2)" :key="'postdoc-' + index"
                  @click="selectQuestion(question)"
                  class="w-full text-left p-2 rounded-lg bg-white/5 hover:bg-white/10 text-white/70 hover:text-white transition-all duration-200 text-xs">
                  {{ ts(question) }}
                </button>
              </div>
            </div>

            <!-- 企业优惠问题 -->
            <div class="mb-2">
              <h5 class="text-sm font-medium text-electric-500 mb-2">🏢 {{ ts('企业优惠') }}</h5>
              <div class="space-y-1">
                <button v-for="(question, index) in enterpriseQuestions.slice(0, 2)" :key="'enterprise-' + index"
                  @click="selectQuestion(question)"
                  class="w-full text-left p-2 rounded-lg bg-white/5 hover:bg-white/10 text-white/70 hover:text-white transition-all duration-200 text-xs">
                  {{ ts(question) }}
                </button>
              </div>
            </div>

            <!-- 出口贸易问题 -->
            <div class="mb-2">
              <h5 class="text-sm font-medium text-electric-500 mb-2">🌐 {{ ts('出口贸易') }}</h5>
              <div class="space-y-1">
                <button v-for="(question, index) in exportQuestions.slice(0, 2)" :key="'export-' + index"
                  @click="selectQuestion(question)"
                  class="w-full text-left p-2 rounded-lg bg-white/5 hover:bg-white/10 text-white/70 hover:text-white transition-all duration-200 text-xs">
                  {{ ts(question) }}
                </button>
              </div>
            </div>
          </div>
        </div>

        <!-- 相关政策 -->
        <div class="glass-card p-3">
          <h4 class="text-lg font-semibold text-white mb-2 flex items-center">
            <FileText class="w-5 h-5 mr-2 text-electric-500" />
            {{ ts('相关政策') }}
          </h4>
          <div class="space-y-2 overflow-y-auto max-h-56">
            <div v-for="(policy, index) in currentRelatedPolicies" :key="index"
              class="p-3 rounded-lg bg-white/5 hover:bg-white/10 transition-all duration-200 cursor-pointer"
              @click="askAboutPolicy(policy)">
              <h5 class="text-white text-sm font-medium mb-1">{{ ts(policy.title) }}</h5>
              <p class="text-white/70 text-xs mb-2">{{ ts(policy.department) }}</p>
              <div class="flex items-center justify-between">
                <span class="text-electric-500 text-xs">{{ policy.date }}</span>
                <span :class="[
                  'text-xs px-2 py-1 rounded',
                  policy.status === '生效中' ? 'bg-green-500/20 text-green-400' : 'bg-yellow-500/20 text-yellow-400'
                ]">
                  {{ ts(policy.status) }}
                </span>
              </div>
            </div>
            <div v-if="currentRelatedPolicies.length === 0" class="text-center text-white/50 text-sm py-4">
              <FileText class="w-8 h-8 mx-auto mb-2 opacity-50" />
              {{ ts('暂无相关政策') }}
            </div>
          </div>
        </div>

        <!-- 知识导图 -->
        <div class="glass-card p-3">
          <h4 class="text-lg font-semibold text-white mb-2 flex items-center">
            <Network class="w-5 h-5 mr-2 text-electric-500" />
            {{ ts('知识导图') }}
          </h4>
          <div class="bg-white/5 rounded-lg flex items-center justify-center mb-3 overflow-hidden relative h-48">
            <!-- 动态图谱显示 -->
            <div v-if="currentTopicType !== 'none'" class="w-full h-full p-2">
              <!-- 博士后政策图谱 -->
              <div v-if="currentTopicType === 'postdoc'" class="w-full h-full relative">
                <div class="absolute inset-0 flex items-center justify-center">
                  <!-- 中心节点 -->
                  <div class="relative">
                    <div
                      class="w-12 h-12 bg-electric-500 rounded-full flex items-center justify-center text-white text-xs font-bold">
                      {{ ts('博士后') }}
                    </div>

                    <!-- 连接线和子节点 -->
                    <!-- 资助政策 -->
                    <div class="absolute -top-6 -left-16">
                      <div
                        class="w-8 h-8 bg-tech-blue-400 rounded-full flex items-center justify-center text-white text-xs">
                        {{ ts('资助') }}
                      </div>
                    </div>

                    <!-- 生活补贴 -->
                    <div class="absolute -top-6 -right-16">
                      <div
                        class="w-8 h-8 bg-green-400 rounded-full flex items-center justify-center text-white text-xs">
                        {{ ts('补贴') }}
                      </div>
                    </div>

                    <!-- 就业支持 -->
                    <div class="absolute -bottom-6 -left-16">
                      <div
                        class="w-8 h-8 bg-yellow-400 rounded-full flex items-center justify-center text-white text-xs">
                        {{ ts('就业') }}
                      </div>
                    </div>

                    <!-- 住房政策 -->
                    <div class="absolute -bottom-6 -right-16">
                      <div
                        class="w-8 h-8 bg-purple-400 rounded-full flex items-center justify-center text-white text-xs">
                        {{ ts('住房') }}
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              <!-- 企业政策图谱 -->
              <div v-else-if="currentTopicType === 'enterprise'" class="w-full h-full relative">
                <div class="absolute inset-0 flex items-center justify-center">
                  <!-- 中心节点 -->
                  <div class="relative">
                    <div
                      class="w-12 h-12 bg-electric-500 rounded-full flex items-center justify-center text-white text-xs font-bold">
                      {{ ts('企业') }}
                    </div>

                    <!-- 税收优惠 -->
                    <div class="absolute -top-6 -left-16">
                      <div
                        class="w-8 h-8 bg-tech-blue-400 rounded-full flex items-center justify-center text-white text-xs">
                        {{ ts('税收') }}
                      </div>
                    </div>

                    <!-- 研发补贴 -->
                    <div class="absolute -top-6 -right-16">
                      <div
                        class="w-8 h-8 bg-green-400 rounded-full flex items-center justify-center text-white text-xs">
                        {{ ts('研发') }}
                      </div>
                    </div>

                    <!-- 融资支持 -->
                    <div class="absolute -bottom-6 -left-16">
                      <div
                        class="w-8 h-8 bg-yellow-400 rounded-full flex items-center justify-center text-white text-xs">
                        {{ ts('融资') }}
                      </div>
                    </div>

                    <!-- 数字化转型 -->
                    <div class="absolute -bottom-6 -right-16">
                      <div
                        class="w-8 h-8 bg-purple-400 rounded-full flex items-center justify-center text-white text-xs">
                        {{ ts('数字化') }}
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              <!-- 通用政策图谱 -->
              <div v-else-if="currentTopicType === 'general'" class="w-full h-full relative">
                <div class="absolute inset-0 flex items-center justify-center">
                  <!-- 中心节点 -->
                  <div class="relative">
                    <div
                      class="w-12 h-12 bg-electric-500 rounded-full flex items-center justify-center text-white text-xs font-bold">
                      {{ ts('政策') }}
                    </div>

                    <!-- 财税政策 -->
                    <div class="absolute -top-6 -left-16">
                      <div
                        class="w-8 h-8 bg-tech-blue-400 rounded-full flex items-center justify-center text-white text-xs">
                        {{ ts('财税') }}
                      </div>
                    </div>

                    <!-- 产业政策 -->
                    <div class="absolute -top-6 -right-16">
                      <div
                        class="w-8 h-8 bg-green-400 rounded-full flex items-center justify-center text-white text-xs">
                        {{ ts('产业') }}
                      </div>
                    </div>

                    <!-- 就业政策 -->
                    <div class="absolute -bottom-6 -left-16">
                      <div
                        class="w-8 h-8 bg-yellow-400 rounded-full flex items-center justify-center text-white text-xs">
                        {{ ts('就业') }}
                      </div>
                    </div>

                    <!-- 环保政策 -->
                    <div class="absolute -bottom-6 -right-16">
                      <div
                        class="w-8 h-8 bg-purple-400 rounded-full flex items-center justify-center text-white text-xs">
                        {{ ts('环保') }}
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              <!-- 出口贸易图谱 -->
              <div v-else-if="currentTopicType === 'export'" class="w-full h-full relative">
                <div class="absolute inset-0 flex items-center justify-center">
                  <!-- 中心节点 -->
                  <div class="relative">
                    <div
                      class="w-12 h-12 bg-electric-500 rounded-full flex items-center justify-center text-white text-xs font-bold">
                      {{ ts('出口') }}
                    </div>

                    <!-- FCC认证 -->
                    <div class="absolute -top-6 -left-16">
                      <div
                        class="w-8 h-8 bg-tech-blue-400 rounded-full flex items-center justify-center text-white text-xs">
                        {{ ts('FCC') }}
                      </div>
                    </div>

                    <!-- UL认证 -->
                    <div class="absolute -top-6 -right-16">
                      <div
                        class="w-8 h-8 bg-green-400 rounded-full flex items-center justify-center text-white text-xs">
                        {{ ts('UL') }}
                      </div>
                    </div>

                    <!-- 退税政策 -->
                    <div class="absolute -bottom-6 -left-16">
                      <div
                        class="w-8 h-8 bg-yellow-400 rounded-full flex items-center justify-center text-white text-xs">
                        {{ ts('退税') }}
                      </div>
                    </div>

                    <!-- 原产地 -->
                    <div class="absolute -bottom-6 -right-16">
                      <div
                        class="w-8 h-8 bg-purple-400 rounded-full flex items-center justify-center text-white text-xs">
                        {{ ts('原产地') }}
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 默认显示 -->
            <div v-else class="text-center">
              <Network class="w-8 h-8 text-electric-500 mx-auto mb-2" />
              <p class="text-white/70 text-xs">{{ ts('开始对话查看政策图谱') }}</p>
            </div>
          </div>
          <button @click="viewFullMap" :disabled="currentTopicType === 'none'" class="w-full cyber-button text-sm py-2"
            :class="currentTopicType === 'none' ? 'opacity-50 cursor-not-allowed' : ''">
            {{ ts('查看完整导图') }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {
  MessageSquare,
  Send,
  User,
  Bot,
  Sparkles,
  Network,
  FileText,
  ChevronDown
} from 'lucide-vue-next'
import { useTranslation } from '../composables/useTranslation.js'
import { themeState } from '../services/themeService.js'

export default {
  name: 'AIChat',
  components: {
    MessageSquare,
    Send,
    User,
    Bot,
    Sparkles,
    Network,
    FileText,
    ChevronDown
  },
  setup() {
    const { ts } = useTranslation()
    return {
      ts,
      themeState
    }
  },
  data() {
    return {
      messages: [
        {
          id: 1,
          type: 'bot',
          content: '您好！我是AI政策分析助手，可以帮您解答各类政策问题。您可以从右侧常见问题中选择，或直接输入问题咨询。',
          timestamp: new Date()
        }
      ],
      inputMessage: '',
      isLoading: false,
      showQuestions: false,

      // 通用政策问题
      generalQuestions: [
        '最新的税收优惠政策有哪些？',
        '如何申请小微企业扶持政策？',
        '数字化转型有什么补贴政策？',
        '环保相关的政策法规是什么？',
        '创新创业有哪些扶持政策？',
        '就业补贴政策如何申请？'
      ],

      // 博士后相关问题
      postdocQuestions: [
        '博士后进站有哪些优惠政策？',
        '博士后科研资助如何申请？',
        '博士后出站后就业扶持政策？',
        '博士后税收优惠政策详情？',
        '博士后住房补贴申请条件？',
        '博士后科研启动费标准？'
      ],

      // 企业优惠问题
      enterpriseQuestions: [
        '高新技术企业认定优惠政策？',
        '小微企业税收减免如何申请？',
        '企业研发费用加计扣除政策？',
        '制造业企业数字化改造补贴？',
        '出口退税政策最新变化？',
        '企业社保减免政策详情？'
      ],

      // 出口贸易问题
      exportQuestions: [
        '中国出口电子产品到美国需要哪些认证？',
        '出口企业如何申请原产地证书？',
        '跨境电商税收政策有哪些？',
        '出口商品质量认证流程？',
        '国际贸易合规要求详解？',
        '出口信用保险如何办理？'
      ],

      // 相关政策列表
      relatedPolicies: [
        {
          title: '关于支持小微企业发展的若干措施',
          department: '财政部',
          date: '2024-01-15',
          status: '生效中',
          type: 'enterprise',
          category: '企业优惠'
        },
        {
          title: '数字化转型专项扶持政策',
          department: '工信部',
          date: '2024-01-10',
          status: '生效中',
          type: 'enterprise',
          category: '企业优惠'
        },
        {
          title: '高新技术企业认定管理办法',
          department: '科技部',
          date: '2023-12-20',
          status: '生效中',
          type: 'enterprise',
          category: '企业优惠'
        },
        {
          title: '博士后科学基金资助管理办法',
          department: '人社部',
          date: '2024-01-08',
          status: '生效中',
          type: 'postdoc',
          category: '博士后政策'
        },
        {
          title: '博士后生活补贴实施细则',
          department: '人社部',
          date: '2024-01-12',
          status: '生效中',
          type: 'postdoc',
          category: '博士后政策'
        },
        {
          title: '博士后出站就业绿色通道政策',
          department: '人社部',
          date: '2023-12-25',
          status: '生效中',
          type: 'postdoc',
          category: '博士后政策'
        },
        {
          title: '个人所得税专项附加扣除办法',
          department: '税务总局',
          date: '2024-01-01',
          status: '生效中',
          type: 'general',
          category: '通用政策'
        },
        {
          title: '创新创业扶持政策实施方案',
          department: '发改委',
          date: '2024-01-05',
          status: '生效中',
          type: 'general',
          category: '通用政策'
        },
        {
          title: '绿色金融发展指导意见',
          department: '央行',
          date: '2024-01-05',
          status: '即将生效',
          type: 'general',
          category: '通用政策'
        },
        {
          title: '电子产品出口美国认证管理办法',
          department: '商务部',
          date: '2024-01-20',
          status: '生效中',
          type: 'export',
          category: '出口贸易'
        },
        {
          title: 'FCC认证申请指导意见',
          department: '商务部',
          date: '2024-01-18',
          status: '生效中',
          type: 'export',
          category: '出口贸易'
        },
        {
          title: '出口商品原产地证书管理规定',
          department: '海关总署',
          date: '2024-01-12',
          status: '生效中',
          type: 'export',
          category: '出口贸易'
        },
        {
          title: '跨境电商税收优惠政策',
          department: '税务总局',
          date: '2024-01-15',
          status: '生效中',
          type: 'export',
          category: '出口贸易'
        }
      ],
      currentRelatedPolicies: [],
      currentTopicType: 'none'
    }
  },
  watch: {
    messages: {
      handler() {
        this.scrollToBottom();
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    scrollToBottom() {
      this.$nextTick(() => {
        const container = this.$refs.chatContainer;
        container.scrollTop = container.scrollHeight;
      });
    },
    async sendMessage() {
      if (!this.inputMessage.trim()) return

      const userMessage = {
        id: this.messages.length + 1,
        type: 'user',
        content: this.inputMessage,
        timestamp: new Date()
      }

      this.messages.push(userMessage)
      const question = this.inputMessage
      this.inputMessage = ''
      this.isLoading = true

      try {
        // 调用API获取回答
        const response = await this.fetchAIResponse(question)

        const botMessage = {
          id: this.messages.length + 1,
          type: 'bot',
          content: this.formatAPIResponse(response),
          timestamp: new Date()
        }

        this.messages.push(botMessage)

        // 更新相关政策和知识图谱
        this.updateRelatedPolicies(question)

      } catch (error) {
        console.error('API调用失败:', error)
        const botMessage = {
          id: this.messages.length + 1,
          type: 'bot',
          content: error.message || '抱歉，我不太明白您的意思，请重新输入。',
          timestamp: new Date()
        }
        this.messages.push(botMessage)
      } finally {
        this.isLoading = false
        this.scrollToBottom()
      }
    },

    async fetchAIResponse(question) {
      try {
        const response = await fetch('http://localhost:8000/api/query', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            question: question,
            k: 3,
            score_threshold: 0.4
          })
        })

        if (!response.ok) {
          throw new Error(`API请求失败: ${response.status}`)
        }

        return await response.json()
      } catch (error) {
        console.error('API调用错误:', error)
        throw error
      }
    },

    formatAPIResponse(apiResponse) {
      return apiResponse.answer
    },

    updateRelatedPolicies(question) {
      const questionLower = question.toLowerCase()
      let topicType = 'general'

      if (questionLower.includes('博士后') || questionLower.includes('博士')) {
        topicType = 'postdoc'
      } else if (questionLower.includes('企业') || questionLower.includes('公司') ||
        questionLower.includes('高新') || questionLower.includes('小微')) {
        topicType = 'enterprise'
      } else if (questionLower.includes('出口') || questionLower.includes('认证') ||
        questionLower.includes('电子产品') || questionLower.includes('美国') ||
        questionLower.includes('fcc') || questionLower.includes('跨境')) {
        topicType = 'export'
      }

      this.currentTopicType = topicType
      this.currentRelatedPolicies = this.relatedPolicies.filter(policy => policy.type === topicType)
    },

    selectQuestion(question) {
      this.inputMessage = question
      this.showQuestions = false
    },

    handleKeyPress(event) {
      if (event.key === 'Enter' && !event.shiftKey) {
        event.preventDefault()
        this.sendMessage()
      }
    },

    formatTime(timestamp) {
      return new Date(timestamp).toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit'
      })
    },

    askAboutPolicy(policy) {
      this.inputMessage = `请详细介绍一下"${policy.title}"这个政策`
      this.sendMessage()
    },

    viewFullMap() {
      const botMessage = {
        id: this.messages.length + 1,
        type: 'bot',
        content: `正在为您展示${this.getTopicName()}的完整知识导图，包含详细的政策关联关系和实施路径。`,
        timestamp: new Date()
      }
      this.messages.push(botMessage)
      this.scrollToBottom()
    },

    getTopicName() {
      const topicNames = {
        'postdoc': '博士后政策',
        'enterprise': '企业优惠政策',
        'export': '出口贸易政策',
        'general': '通用政策'
      }
      return topicNames[this.currentTopicType] || '政策'
    }
  }
}
</script>

<style scoped>
.glass-card {
  background: rgba(255, 255, 255, 0.05);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 12px;
}

.cyber-input {
  background: rgba(255, 255, 255, 0.07);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 8px;
  color: white;
  transition: all 0.3s ease;
}

.cyber-input:focus {
  border-color: #6e8efb;
  box-shadow: 0 0 0 2px rgba(110, 142, 251, 0.3);
  outline: none;
}

.cyber-input.glow-red {
  box-shadow: 0 0 10px rgba(255, 0, 0, 0.5);
}

.cyber-button {
  background: linear-gradient(135deg, #6e8efb, #a777e3);
  color: white;
  border: none;
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.cyber-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 15px rgba(167, 119, 227, 0.4);
}

.cyber-button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}
</style>